<!--接口日志查询-->
<template>

  <div class="page-container">

    <div class="table-page-body">

      <el-form ref="form" :inline="true" :model="searchValue" style="width: 100%; " class="search-panel">

        <el-form-item :label="$tt('label_keyword')">
          <!-- <common_more_input v-model="searchValue.keyword" clearable></common_more_input> -->
          <el-input v-model.trim="searchValue.keyword" clearable></el-input>
        </el-form-item>

        <el-form-item :label="$tt('label_application')">
          <el-select v-model="searchValue.appId" placeholder=" " clearable @change="applicationChange">
            <el-option v-for="item in appInfoArr" :key="item.appId" :label="item.appName + ' - ' + item.platformName"
              :value="item.appId">
              <span style="float: left">{{ item.appName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ '[' + item.platformCode + ']' +
                item.platformName }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$tt('label_status')">
          <ex-select-auto v-model="searchValue.status"
            :data="[{ label: $tt('label_success'), value: 'SUCCESS' }, { label: $tt('label_fail'), value: 'FAIL' }, { label: $tt('label_doing'), value: 'DOING' }]"
            clearable optionKey="value" optionLabel="label" optionValue="value">
          </ex-select-auto>
        </el-form-item>
        <el-form-item :label="$tt('被调用方')">
          <!-- <ex_super_input v-model="searchValue.apiTo" type="select" enum="ApiRoleEnum"> </ex_super_input> -->
          <ex_super_input v-model="searchValue.apiTo"> </ex_super_input>
        </el-form-item>

        <el-form-item :label="$tt('label_interfaces')">


          <el-select v-model="searchValue.apiUrl" clearable placeholder="" filterable>
            <el-option-group v-for="group, groupIndex in apiDataList" :key="'group_' + groupIndex" :label="group.name">
              <el-option v-for="item in group.children" :key="item.apiUrl" :label="item.apiName" :value="item.apiUrl">
              </el-option>
            </el-option-group>
          </el-select>

        </el-form-item>


        <el-form-item :label="$tt('label_tms_user_time')">
          <el-date-picker value-format="timestamp" v-model="searchValue.happenTime1" type="date"
            :placeholder="$tt('label_start_time')" style="max-width: 138px;" :clearable="false"></el-date-picker>
          <el-date-picker value-format="timestamp" v-model="searchValue.happenTime2" type="date"
            :placeholder="$tt('label_end_time')" style="max-width: 138px;"></el-date-picker>
        </el-form-item>

        <el-button class="queryBtn" type="primary" icon="el-icon-search"
          @click="$refs['gridPanelEl'].loadData(searchValue)">
          {{ $tt('label_query') }}
        </el-button>
        <el-button class="queryBtn" @click="searchValue = defaultSearchValue">{{ $tt('label_reset') }}</el-button>
        <!--      <el-button class="queryBtn" @click="batchRetry()">批量重试</el-button>-->

      </el-form>
      <div class="action">
        <el-button type="primary" @click="requestYiCang">
          易仓重试
        </el-button>
      </div>
      <!-- grid panel  -->
      <ex-table-auto ref="gridPanelEl" class="el-table-nowwarp table-flex ex_table_auto" :url="queryUrl" autoFill
        autoPage border @selection-change="handleSelectionChange" :autoLoad="false">

        <el-table-column type="selection" width="40" align="center"></el-table-column>

        <el-table-column type="index" label="#" width="52" align="center">
          <template slot-scope="scope">
            {{
              ($refs['gridPanelEl'].getLastRequestParam().pageIndex - 1) *
              $refs['gridPanelEl'].getLastRequestParam().pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>

        <el-table-column prop="happenTime" :label="$tt('label_happen_time')" min-width="14">
          <template slot-scope="scope">
            {{ $dateFormat(scope.row.happenTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="platformCode" :label="$tt('label_platform')" min-width="14">
          <template slot-scope="scope">
            [{{ scope.row.platformCode }}] {{ scope.row.platformName }}
          </template>
        </el-table-column>

        <el-table-column prop="apiName" :label="$tt('label_interfaces_name')" min-width="16" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ apiUrlCahce[scope.row.apiUrl] ? apiUrlCahce[scope.row.apiUrl].apiName : scope.row.apiUrl }}
            <span style="color: #999;" v-if="scope.row.apiType == 'ResponseApi'">[{{ $tt('label_notice') }}]</span>
          </template>
        </el-table-column>

        <el-table-column prop="apiTo" :label="$tt('被调用方')" min-width="20">
          <!-- <template slot-scope="scope">
            {{ $t('ApiRoleEnum_' + scope.row.apiTo) }}
          </template> -->
        </el-table-column>
        <el-table-column prop="timeCost" :label="$tt('label_time_consumption_ms')" min-width="7"
          align="right"></el-table-column>

        <el-table-column prop="status" :label="$tt('label_status')" min-width="8" align="center">
          <template slot-scope="scope">
            <font v-if="scope.row.status === 'SUCCESS'">{{ $tt('label_success') }}</font>
            <font v-if="scope.row.status === 'DOING'">{{ $tt('label_doing') }}</font>
            <font style="color: red;" v-if="scope.row.status === 'FAIL'">{{ $tt('label_fail') }}</font>
            <font v-if="scope.row.retryTime > 1">({{ scope.row.retryTime }})</font>
          </template>
        </el-table-column>

        <el-table-column prop="requestJson" :label="$tt('label_request')" min-width="20">
          <template slot-scope="scope">

            <el-popover placement="right" width="500" trigger="hover" @after-leave="jsonViewType = 1">
              <div>
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px; ">
                  <el-button
                    type="text"
                    @click="
                      $copyToClip(
                        jsonViewType==1  ? scope.row.requestJson : scope.row.sourceRequestJson,
                        $t('tip_has_copy_to_clip')
                       )"   >
                    {{$t('label_copy')}}
                  </el-button>


                  <el-radio-group v-if="scope.row.sourceRequestJson" v-model="jsonViewType">
                    <el-radio-button label="1">{{ $tt('label_Communication_message') }}</el-radio-button>
                    <el-radio-button label="2">{{ $tt('label_Original_message') }}</el-radio-button>
                  </el-radio-group>
                </div>

                <div v-if="jsonViewType == 1" style="line-height: 32px;">
                  {{ maxLenghTrim(scope.row.requestJson, 1000) }}
                </div>
                <div v-else style="line-height: 32px;">
                  {{ maxLenghTrim(scope.row.sourceRequestJson, 1000) }}
                </div>

              </div>

              <span slot="reference">{{ maxLenghTrim(scope.row.requestJson, 50) }}</span>

            </el-popover>



          </template>
        </el-table-column>

        <el-table-column prop="errorMessage" :label="$tt('label_response')" min-width="18">
          <template slot-scope="scope">
            <el-tooltip placement="left" effect="light">
              <div slot="content" style="line-height: 24px; width: 300px; font-size: 14px; ">
                {{ scope.row.errorMessage ? scope.row.errorMessage : scope.row.responseJson }}
              </div>
              <font>{{ scope.row.errorMessage ? scope.row.errorMessage : scope.row.responseJson }}</font>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="" align="center" width="80">
          <template slot-scope="scope">
            <el-button :disabled="scope.row.apiType === 'RequestApi'" @click="
              retryForm = { requestId: scope.row.requestId, requestJson: scope.row.requestJson };
            dialogFormVisible = true;
            " type="text" size="medium">
              {{ $tt('label_retry') }}
            </el-button>
          </template>
        </el-table-column>

      </ex-table-auto>

      <!-- Form -->

      <el-dialog :title="$tt('label_callback_retry')" :visible.sync="dialogFormVisible">

        <el-form :model="retryForm" style="padding-top: 0px; padding-bottom: 0px;">
          <el-form-item :label="$tt('label_request_param')">
            <code-editor v-model="retryForm.requestJson" height="400px"></code-editor>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $tt('label_cancel') }}</el-button>
          <el-button type="primary" @click="retryRequest()" :disabled="saveButtonDisabled">{{ $tt('label_confirm')
            }}</el-button>
        </div>

      </el-dialog>


    </div>

  </div>
</template>
<script>

import CodeEditor from '@/component/base/code-editor.vue'
export default {

  title: 'label_api_interface_log_query',

  components: { CodeEditor },

  data() {
    let day1 = new Date().getTime()

    let day = new Date();

    day.setHours(0)
    day.setMinutes(0)
    day.setSeconds(0)
    day.setMilliseconds(0)

    let today = day.getTime()

    return {
      jsonViewType: 1,

      saveButtonDisabled: false,
      isShow: false,
      rowData: {},

      defaultSearchValue: {
        "appNameAndApiCode": "",
        "status": "",
        "happenTime1": today,
        "happenTime2": today
      },

      searchValue: {
        "appNameAndApiCode": "",
        "status": "",
        "happenTime1": today,
        "happenTime2": today
      },
      configValueTime: '',

      queryUrl: '',

      dialogFormVisible: false,
      retryForm: {
        requestId: '',
        requestJson: ''
      },
      multipleSelection: [],


      apiDataList: [],
      apiUrlCahce: {},

      appInfoArr: []

    };
  },

  created() {
    var _this = this

    _this.queryUrl = '/open-api/open/OpenApiConfigRpc/queryOpenRequestMessage.json'

    _this.$getAllDocs(function (docs) {

      let apiUrlCahce = {}

      _this.erpGroups = docs.ERP
      _this.wmsGroups = docs.WMS

      _this.erpGroups.forEach(group => {
        group.name = '[ERP] ' + group.name
        group.children.forEach(c => {
          apiUrlCahce[c.apiUrl] = c
        })
      })
      _this.wmsGroups.forEach(group => {
        group.name = '[WMS] ' + group.name
        group.children.forEach(c => {
          apiUrlCahce[c.apiUrl] = c
        })
      })

      _this.apiDataList = docs.ERP.concat(docs.WMS)
      _this.apiUrlCahce = apiUrlCahce

    })


    _this.$ajax({
      url: '/open-api/open/OpenAppRpc/queryAllAppSimple.json',
      success(res) {
        if (res && res.data && res.data.rows) {
          _this.appInfoArr = res.data.rows
        }
      }
    })

  },

  mounted() {

    let _this = this

    _this.$refs['gridPanelEl'].loadData(_this.searchValue)
    //this.resetHeight()
  },

  props: {

    'windowHeight': {
      type: Number,
      default: -1
    },

  },

  destroyed() {
  },

  methods: {

    resetHeight2() {
      this.$refs['gridPanelEl'].setHeight(window.innerHeight - 229)
    },

    resetHeight() {
      //
      //this.$refs['gridPanelEl'].setHeight((window.innerHeight - 400) + 'px')
      //this.$refs['gridPanelEl'].autoResizeHeight()
    },

    maxLenghTrim(str, len) {
      if (!str) {
        return ''
      }
      if (str.length < len) {
        return str
      }
      return str.substring(0, len) + '...'
    },

    batchRetry() {
      let _this = this
      if (this.multipleSelection.length == 0) {
        _this.$message({
          type: 'error',
          message: _this.$tt('tip_no_select_record')
        })
        return
      }


      let ids = this.multipleSelection.filter(e => e.transferType == 'haiq_to_customer' && e.status == 'fail').map(e => e.requestId)

      if (!ids || ids.length == 0) {
        _this.$message({
          type: 'error',
          message: '没有需要重试的记录，批量重试只针对调用方向为"haiq > customer" 状态为"失败"的记录'
        })
        return
      }

      this.$confirm('本操作只针对调用方向为"haiq > customer" 状态为"失败"的记录<br/>当前可重试记录数为 ' + ids.length + ', 是否继续?', '提示', {
        dangerouslyUseHTMLString: true,
        customClass: 'retry-dialog-message',
        width: 300,
        type: 'warning'
      }).then(() => {

        _this.$ajax({
          url: '/open-api/document/AutoDocumentRpc/batchRetryRequest.json',
          data: {
            "ids": ids.join(',')
          },
          success(res) {
            _this.$message({
              showClose: true,
              message: _this.$tt('tip_operate_success'),
              type: 'success'
            })
            _this.$refs['gridPanelEl'].loadData()
          }
        })

      }).catch(() => {

      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    showData(data) {
      this.rowData = data.row
      this.isShow = true
    },

    retryRequest() {

      let _this = this

      _this.saveButtonDisabled = true

      _this.$ajax({
        url: '/open-api/open/OpenApiConfigRpc/retryRequest.json',
        data: _this.retryForm,
        success(res) {
          _this.$message({
            showClose: true,
            message: _this.$tt('tip_operate_success'),
            type: 'success'
          })
          _this.$refs['gridPanelEl'].loadData()
          _this.dialogFormVisible = false
          _this.saveButtonDisabled = false
        },

        afterAjax() {
          _this.saveButtonDisabled = false
          _this.saveButtonDisabled = false
        }
      })

    },
    requestYiCang() {
      this.$confirm('是否确定操作易仓重试?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: '/open-api/open/OpenApiConfigRpc/retryRequestYiCang.json',
          data: { ...this.searchValue, requestIdList: this.multipleSelection.map(it => it.requestId).filter(it => it) },
          type: 'json',
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$t('tip_operate_success'),
              type: 'success'
            })
            this.$refs['gridPanelEl'].loadData()
          },
        })
      })

    },
    applicationChange(e){
      if(e){
        const obj = this.appInfoArr.find(item=>item.appId ===e)
        this.searchValue.platformCode = obj.platformCode
      }else{
        this.searchValue.platformCode = ''
      }

    }


  }
};

</script>
<style scoped lang="less">
.retry-dialog-message {
  width: 500px;
}

.action {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}
</style>
